package common.helper.json;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;

/**
 * Created by julianzliu on 4/20/2017.
 */
public class JavaToJsonString {

    public static String mapJavaToPrettyJson(Object object){
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        String json = "";
        try {
            json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    public static String mapJavaToRestJson(Object object){
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        //mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        //mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        String json = "";
        try {
            //json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
            json = mapper.writeValueAsString( object );
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }


    public static String mapJavaToJson(Object object){
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        //mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        //mapper.enable(SerializationFeature.INDENT_OUTPUT);
        //mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
        //mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        String json = "";
        try {
            //json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
            json = mapper.writeValueAsString( object );
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}
